<template>
  <div>
    <div class="projection_box">
      <TabPoint :pointList="pointList"></TabPoint>

      <div class="content" id="pointBox">
        <!-- 查询 -->
        <Search :form="searchForm" v-model="searchForm"></Search>
        <!-- 流处理 -->
        <FlowHnadle ref="flowHnadleRef"></FlowHnadle>
        <!-- 注解 -->
        <Notes :items="treeItems" ref="notesRef"></Notes>
        <!-- 投影 -->
        <Projection
          :attributeList="attributeList"
          v-model="grouping"
          :extensionsLR="extensionsLR"
        ></Projection>
        <!-- 输出 -->
        <Output
          @handDelOrderBy="handDelOrderBy"
          @handAddOrderBy="handAddOrderBy"
          :attributeList="attributeList"
          v-model="output"
        ></Output>
      </div>
    </div>
    <!-- 确认取消公共组件 -->
    <top-operation-button @submit="submit" @handClose="handClose" />
  </div>
</template>

<script>
import TopOperationButton from "../CommonComponents/TopOperationButton";
import TabPoint from "@/components/TabPoint";
import Search from "./component/Search.vue";
import FlowHnadle from "./component/FlowHandle.vue";
import Notes from "./component/Notes.vue";
import Projection from "@/components/Projection";
import Output from "@/components/Output";
import { getMetadata } from "@/api/project";
import { validate } from "./js/validate";
import {
  mapParameterValues,
  obtainStreamFunctionsFromResponse,
} from "../windowsPage/js/index";
import {
  setFunctiondata,
  setStreamHandlerList,
  settargetCellAttr,
  setSourceCellAttr,
  setUserAttr,
  setTypeName,
} from "./js/index";
import { mapGetters } from "vuex";
import { generateId, reverseJson, empty } from "@/utils/index";
import _ from "lodash";
export default {
  components: {
    TopOperationButton,
    Output,
    TabPoint,
    Search,
    FlowHnadle,
    Notes,
    Projection,
  },
  computed: {
    ...mapGetters(["extensions", "metadata"]),
    // 后一个节点的属性
    relateData() {
      // relateData.targetCell.name
      return this.$store.state.projection.relateData;
    },
    extensionsLR() {
      if (JSON.stringify(this.$store.state.projection.extensions) !== "{}") {
        let attrArr =
          this.$store.state.projection.extensions.funArr.find(
            (item) => item.name == "属性"
          )?.list || [];
        return attrArr;
      } else {
        return [];
      }
    },
  },
  data() {
    return {
      // 查询
      searchForm: {
        queryName: "",
        from: "",
      },
      // 输出
      output: {
        orderCh: false,
        orderBy: [], //按属性排序
        checkedLimit: false, //限制
        limit: "",
        checkedOffset: false, //位移
        offset: "",
        checkedOutputRateLimit: false, //输出速率
        outputRateLimit: "",
        // 操作下边的数据
        queryOutput: {
          type: "INSERT",
          target: "", //插入
          output: {
            eventType: "CURRENT_EVENTS", //事件类型
            // set选中传-选中整个都不传
            checkedSet: false,
            set: [],
          },
          on: "",
        },
      },
      // 投影
      grouping: {
        groupBy: [], //按属性分组
        having: "", //过滤
        attrChecked: false,
        checkedFilter: false,
        select: {
          type: "ALL", //ALL USER_DEFINED 所有属性,用户自定义属性
          value: [], //用户自定义属性
        },
      },
      treeItems: [],
      form: { name: "" },
      rules: {},
      firstAttr: {},
      pointList: [
        {
          name: "查询",
          id: "searchPoin",
          val: "searchPoin",
        },
        {
          name: "流处理",
          id: "handlePoin",
          val: "handlePoin",
        },
        {
          name: "注释",
          id: "notesPoin",
          val: "notesPoin",
        },
        {
          name: "投影",
          id: "prijectionPoin",
          val: "prijectionPoin",
        },
        {
          name: "输出",
          id: "output",
          val: "output",
        },
      ],
      attributeList: [],
      streamHandlerList: [],
      targetCellAttr: [],
    };
  },
  props: {
    nodeDataRight: {
      type: Object,
      default: () => {},
    },
  },
  watch: {
    nodeDataRight: {
      handler: async function (newData, oldData) {
        let tempdata = _.cloneDeep(newData);
        const { objectState } = tempdata;
        // 传递节点数据-合并metadata的数据
        this.$store.commit("projection/setExtensions", {
          relateData: this.nodeDataRight.relateData,
        });
        const {
          limit,
          offset,
          outputRateLimit,
          queryOutput,
          orderBy,
          groupBy,
          having,
          select,
          queryName,
          queryInput,
          annotationListObjects,
        } = tempdata;
        console.log(tempdata, "节点信息");
        this.searchForm.queryName = tempdata.queryName || "";
        const name = tempdata.relateData.targetCell.name;
        this.searchForm.from = tempdata.relateData.sourceCell.name;
        // 后一个节点属性整理
        if (tempdata.relateData.targetCell.attributeList)
          tempdata.relateData.targetCell.attributeList =
            tempdata.relateData.targetCell.attributeList = settargetCellAttr(
              tempdata.relateData.targetCell.attributeList,
              name
            );
        if (tempdata.relateData.sourceCell.attributeList)
          tempdata.relateData.sourceCell.attributeList = setSourceCellAttr(
            tempdata.relateData.sourceCell.attributeList
          );

        this.$store.commit("projection/setRelateData", tempdata.relateData);
        this.targetCellAttr = tempdata.relateData.targetCell.attributeList;
        // 设置来源节点名称
        // this.$store.commit(
        //   "projection/setQueryInput",
        //   tempdata.relateData.sourceCell.name
        // );
        if (tempdata.relateData.sourceCell) {
          this.attributeList = _.cloneDeep(
            tempdata.relateData.sourceCell.attributeList
          );
          // this.grouping = [
          //   { id: generateId(), name: "", attributeList: this.attributeList },
          // ];
          this.attributeList &&
            this.attributeList.forEach((item) => {
              item.id = generateId();
              item.value = item.name;
              item.disabled = false;
            });
        }

        this.$nextTick(async () => {
          // 获取整理的抽屉数据-同步处理
          // await this.$store.dispatch(
          //   "projection/getMetadata",
          //   this.nodeDataRight.relateData
          // );

          // 封装流处理数据
          if (queryInput && queryInput.streamHandlerList.length !== 0) {
            // console.log(this.getFunNamePar(queryInput.streamHandlerList));
            // this.getFunNamePar(queryInput.streamHandlerList);
            queryInput.streamHandlerList = this.getFunNamePar(
              queryInput.streamHandlerList
            );
            // queryInput.streamHandlerList = setStreamHandlerList(
            //   queryInput.streamHandlerList || [],
            //   this.extensions
            // );
            if (this.$refs.flowHnadleRef) {
              this.$refs.flowHnadleRef.streamHandlerList =
                queryInput && queryInput.streamHandlerList;
              this.$refs.flowHnadleRef.streamHandlerChecked = true;
            }
          } else {
            this.$refs.flowHnadleRef.streamHandlerChecked = false;
          }

          // queryInput.streamHandlerList
        });

        if (annotationListObjects && annotationListObjects.length !== 0) {
          this.$nextTick(() => {
            // 自定义注解整理
            this.$refs.notesRef.treeItems = reverseJson(
              annotationListObjects,
              "dist"
            );
          });
          // treeData
          // const { name, elements } = annotationListObjects[0];
          const index = annotationListObjects.findIndex(
            (i) => i.name == "dist"
          );
          // dist数据整理回显
          if (index != -1) {
            this.$nextTick(() => {
              this.$refs.notesRef.form = {
                parallel: annotationListObjects[index].elements.find(
                  (item) => item.key == "parallel"
                ).value,
                execGroup: annotationListObjects[index].elements.find(
                  (item) => item.key == "execGroup"
                ).value,
                checkedImplement: annotationListObjects[index].elements.find(
                  (item) => item.key == "execGroup"
                ).value
                  ? true
                  : false,
                checkedParallel: annotationListObjects[index].elements.find(
                  (item) => item.key == "parallel"
                ).value
                  ? true
                  : false,
              };
              this.$refs.notesRef.checked = true; //打开async输入框
            });
          } else {
            this.$nextTick(() => {
              this.$refs.notesRef.form = {
                parallel: "",
                execGroup: "",
                checkedParallel: false,
                checkedImplement: false,
              };
              this.$refs.notesRef.checked = false; //打开async输入框
            });
          }
        }
        this.searchForm.queryName = queryName;
        // 输出数据回显
        if (limit) {
          this.output.checkedLimit = true;
        } else {
          this.output.checkedLimit = false;
        }
        if (offset) {
          this.output.checkedOffset = true;
        } else {
          this.output.checkedOffset = false;
        }
        if (orderBy && orderBy.length != 0) {
          this.output.orderCh = true;
          this.output.orderBy = orderBy;
        } else {
          // 如果orderBy没值,给一个默认值,选中的时候方便展示
          this.output.orderCh = false;
          this.output.orderBy = [
            {
              id: generateId(),
              attrValue: "",
              sortValue: "",
              attributeList: this.attributeList,
            },
          ];
        }
        if (outputRateLimit) {
          this.output.checkedOutputRateLimit = true;
        } else {
          this.output.checkedOutputRateLimit = false;
        }
        this.output = {
          ...this.output,
          limit,
          offset,
          outputRateLimit,
        };
        // set有值
        this.output.queryOutput.target = tempdata.relateData.targetCell.name;
        if (queryOutput && queryOutput.output.eventType) {
          this.output.queryOutput.output.eventType =
            queryOutput.output.eventType;
        }
        if (
          queryOutput &&
          queryOutput.output.set &&
          queryOutput.output.set.length !== 0
        ) {
          this.output.queryOutput.output.checkedSet = true;
        } else {
          this.output.queryOutput.output.checkedSet = false;
        }

        // 判断过滤是否有值-有值打开
        if (having && having != "") {
          this.grouping.checkedFilter = true;
          this.grouping.having = having;
        } else {
          this.grouping.checkedFilter = false;
        }
        // 判断是否是用户自定义
        if (select && select.value && select.value.length !== 0) {
          this.grouping.select.type = select.type;
          // this.grouping.attrChecked = true;
          // 后一个节点的属性名是唯一的 此处要进行合并和后一个节点关联 this.targetCellAttr
          this.grouping.select.value = setUserAttr(
            select.value,
            this.targetCellAttr
          );
        } else {
          // this.grouping.attrChecked = false;
          this.grouping.select.value = setUserAttr([], this.targetCellAttr);
        }
        if (groupBy && groupBy.length != 0) {
          this.grouping.attrChecked = true;
          this.grouping.groupBy = groupBy;
        } else {
          this.grouping.attrChecked = false;
          this.grouping.groupBy = [
            this.attributeList &&
              this.attributeList.length !== 0 &&
              this.attributeList[0].name,
          ];
        }
        if (objectState != "new") {
        }
      },
      immediate: true,
      deep: true,
    },
  },
  mounted() {
    // this.getMetadata();
    // this.grouping.select.value = this.relateData.targetCell.attributeList;
    // // 来源
    // this.searchForm.from = this.relateData.sourceCell.name;
    // // 插入
    // this.output.queryOutput.target = this.relateData.targetCell.name;
    // // 输出-按属性排序
    // this.output.orderBy =
    //   this.relateData.targetCell.attributeList.length !== 0
    //     ? [this.relateData.targetCell.attributeList[0]]
    //     : [];
  },
  methods: {
    getFunNamePar(streamHandlerList) {
      const newstreamHandlerList = _.cloneDeep(streamHandlerList);
      newstreamHandlerList.forEach((item) => {
        item.title = setTypeName(item.type);
        if (item.type !== "FILTER") {
          const key =
            item.type == "WINDOW" ? "windowFunctionNames" : "streamFunctions";
          item.value.parameters = mapParameterValues(
            {
              function: item.value.function,
              parameters: item.value.parameters,
            },
            obtainStreamFunctionsFromResponse(this.metadata)[key]
          );
        }
      });

      return newstreamHandlerList;
    },
    //删除orderBy
    handDelOrderBy(i) {
      this.output.orderBy.splice(i, 1);
    },
    // 添加
    handAddOrderBy() {
      this.output.orderBy.push({
        id: generateId(),
        attrValue: "",
        sortValue: "ASC",
        order: "ASC",
        attributeList: this.attributeList,
      });
    },
    handClose() {
      this.$emit("handClose");
    },
    isCheck() {
      // 在提交 的时候 判断是否选中清空数据
      // 是否有用户自定义属性
      if (this.grouping.select.type == "ALL") {
        // this.grouping.select.value = [];
        this.grouping.select.value = "*";
      }
      // 按属性分组
      if (!this.grouping.attrChecked) {
        this.grouping.groupBy = [];
      }
      // 按过滤分组
      if (!this.grouping.checkedFilter) {
        this.grouping.having = "";
      }
      // 按属性排序
      if (!this.output.orderCh) {
        this.output.orderBy = [];
      }
      // 限制
      if (!this.output.checkedLimit) {
        this.output.limit = undefined;
      }
      // 位移
      if (!this.output.checkedOffset) {
        this.output.offset = undefined;
      }
      // 输出速率
      if (!this.output.checkedOutputRateLimit) {
        this.output.outputRateLimit = undefined;
      }
      // set如果没选中 不传set
      if (!this.output.queryOutput.output.checkedSet) {
        this.output.queryOutput.output.set = undefined;
      }
    },
    submit() {
      // 流处理
      const { streamHandlerList, streamHandlerChecked } =
        this.$refs.flowHnadleRef.getFlowData();
      // 注解
      const notesList = this.$refs.notesRef.getNotes();
      const treeItems = this.$refs.notesRef.treeItems;
      const queryInput = {
        type: "PROJECTION", //PROJECTION
        from: this.searchForm.from,
        streamHandlerList,
        streamHandlerChecked,
      };
      // 判断选择框是否选择-没有选择的清空数据
      this.isCheck();
      // 最终的提交数据
      const WINDOW_FILTER_PROJECTION = {
        // 输出
        ...this.output,
        // 投影
        ...this.grouping,
        // 注解
        ...notesList,
        queryName: this.searchForm.queryName,
        queryInput,
        name: this.searchForm.queryName,
        treeItems: treeItems,
        relateData: this.nodeDataRight.relateData,
      };
      console.log(WINDOW_FILTER_PROJECTION, "最终的数据");
      // 表单验证
      if (validate(WINDOW_FILTER_PROJECTION)) {
        let returnData = {
          display: false,
          type: "queryLists",
          keyType: "WINDOW_FILTER_PROJECTION",
          objectState: this.nodeDataRight.objectState,
          nodeData: WINDOW_FILTER_PROJECTION,
          nodeDataRight: this.nodeDataRight,
        };
        // 存储到vuex-后续不需要可以删除
        this.$emit("returnSource", returnData);
      }
    },
    // async getMetadata() {
    //   const { data } = await getMetadata();
    //   // 数据整理(函数,过滤,窗口)
    //   let extensionsObj = setFunctiondata(data, this.nodeDataRight.relateData);
    //   //存入vuex
    //   this.$store.commit("projection/setMetadata", extensionsObj);
    // },
  },
};
</script>

<style lang='scss' scoped>
.projection_box {
  display: flex;
  width: 100%;
  .content {
    padding-right: 10px;
    width: 100%;
    height: 80vh;
    overflow: scroll;
    overflow-x: hidden;
  }
}
</style>